let fs = require('fs');
let path = require('path')
let express = require('express');
let multer = require('multer');
let { tool } = require("../common/main");

let router = express.Router();
let upload = multer({ dest: 'upload/upload_tmp' });
//上传
router.post('/upload', upload.any(), function (req, res, next) {
    try {
        if (!req.files) throw new Error("请选择文件!");
        let file = req.files[0];
        let src = `${req.session.user ? req.session.user.id : 0}_${new Date().getTime()}.${req.files[0].mimetype.split("/")[1]}`;
        let des_file = `./upload/images/${src}`;
        fs.readFile(file.path, function (err, data) {
            fs.writeFile(des_file, data, function (err) {
                if (err) {
                    tool.rError(res, err);
                } else {
                    tool.rSuccess(res, {
                        data: src
                    });
                }
            });
        });
    } catch (error) {
        tool.rError(res, error);
    }
});
//查看
router.get('/upload/images/*', function (req, res, next) {
    try {
        if (req.url === "/upload/images/") throw new Error("文件不存在");
        let url = path.resolve(__dirname, '..') + req.url;
        fs.exists(url, exists => {
            exists ? res.sendFile(url) : tool.rError(res, new Error("文件不存在"), 404);
        })
    } catch (error) {
        tool.rError(res, error, 404);
    }
});
//查看
router.get('/temp/*', function (req, res, next) {
    try {
        if (req.url === "/temp/") throw new Error("文件不存在");
        let url = path.resolve(__dirname, '..') + req.url;
        fs.exists(url, exists => {
            exists ? res.sendFile(url) : tool.rError(res, new Error("文件不存在"), 404);
        })
    } catch (error) {
        tool.rError(res, error, 404);
    }
});
// router.get('/upimage', function (req, res, next) {
//     res.render("upload");
// });
module.exports = router;